package com.android.geotrack;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.LinkedList;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import android.graphics.drawable.Drawable;
import android.os.Message;
import android.util.Log;

public class LoadTracksRunnable implements Runnable
{
	private TopTracksActivity tta;
	public volatile static boolean ltr_started = false;
	
	public LoadTracksRunnable(TopTracksActivity tta)
	{
		this.tta = tta;
	}
	
	public void run()
	{
		this.ltr_started = true;
		
		List<Track> topTracks = new LinkedList<Track>();
		
		/* Start parsing. */
		try {
			Log.v("TopTracksActivity", "Started parsing.");
			
			// Make URL.
			URL url = new URL("http://geotrack.vankeer.eu/topTracks.php?country=" + tta.country + "&limit=15");
			
	        // Get a SAXParser from the SAXPArserFactory.
	        SAXParserFactory spf = SAXParserFactory.newInstance();
	        SAXParser sp = spf.newSAXParser();

	        // Get the XMLReader of the SAXParser we created.
	        XMLReader xr = sp.getXMLReader();
	        // Create a new ContentHandler and apply it to the XML-Reader.
	        TopTracksParser parser = new TopTracksParser();
	        xr.setContentHandler(parser);
	        
	        // Parse the xml-data from our URL.
	        xr.parse(new InputSource(url.openStream()));
			
			Log.v("TopTracksActivity", "Parsing finished.");
	        
	        /* Parsing has finished. */
	        
	        topTracks = parser.getParseResult();

		} catch (ParserConfigurationException e) {
			Log.e("Exception", e.toString());
		} catch (SAXException e) {
			Log.e("Exception", e.toString());
		} catch (IOException e) {
			Log.e("Exception", e.toString());
		}
		
		// Draw thumbnails
		LinkedList<Drawable> thumbs = new LinkedList<Drawable>();
		for ( Track t : topTracks ) {
			String image = t.getThumbnail_medium();
			if ( image!=null & ! image.equals("") ) {
				try {
					thumbs.add(Drawable.createFromStream(new URL(image).openStream(), ""));
				} catch (MalformedURLException e) {
					Log.e("Exception", e.toString());
				} catch (IOException e) {
					Log.e("Exception", e.toString());
				}
			}
		}				
		
		// Send results
		Message msg = tta.messageHandler.obtainMessage();
		msg.what = 1337;
		Object [] results = new Object[2];
		results[0] = topTracks;
		results[1] = thumbs;
		msg.obj = results;
		tta.messageHandler.sendMessage(msg);
		
		this.ltr_started = false;
	}

}